package models

import (
	"LazyPig/database"
	"errors"
	"fmt"
	"strings"
	"time"
)

type Rule struct {
	Id		int		`form:"id"`
	Name	string	`form:"name" binding:"required"`
	Time	string	`form:"time" binding:"required"`
	Period	[]string	`form:"period" binding:"required"`
	Is		bool		`form:"isAddress"`
	Person	[]string	`form:"person" binding:"required"`
	Lat		float64	`form:"lat"`
	Lng		float64	`form:"lng"`
	Address	string	`form:"address"`
}

func NewRule(r *Rule) (interface{}, error) {
	data := make(map[string]interface{})
	data["name"] = r.Name
	data["time"] = r.Time
	data["isAddress"] = r.Is
	data["period"] = strings.Join(r.Period, ",")
	data["person"] = strings.Join(r.Person, ",")
	data["lat"] = r.Lat
	data["lng"] = r.Lng
	data["address"] = r.Address
	if r.Id == 0 {
		id, err := database.SqlDB.Insert("rule", data)
		if err != nil {
			fmt.Println(err)
			return nil, errors.New("新增失败")
		}
		user := make(map[string]interface{})
		user["rule"] = id
		for _, item := range r.Person {
			go func() {
				_, err = database.SqlDB.Update("user", fmt.Sprintf("id=%s", item), user)
			}()
		}
	} else {
		_, err := database.SqlDB.Update("rule", fmt.Sprintf("id=%v", r.Id), data)
		if err != nil {
			fmt.Println(err)
			return nil, errors.New("修改失败")
		}
		user := make(map[string]interface{})
		user["rule"] = r.Id
		for _, item := range r.Person {
			go func() {
				_, err = database.SqlDB.Update("user", fmt.Sprintf("id=%s", item), user)
			}()
		}
	}

	return nil, nil
}

func GetRuleList() (interface{}, error) {
	rows, err := database.SqlDB.GetAll("SELECT * FROM rule")
	if err != nil {
		return nil, errors.New("查询失败")
	}
	return rows, nil
}

func GetRule(id string)(interface{}, error) {
	row, err := database.SqlDB.GetOne("SELECT * FROM rule WHERE id = ?", id)
	if err != nil {
		return nil, errors.New("查询失败")
	}
	return row, nil
}

func GetCame(id string)(interface{}, error)  {
	toDay := time.Now().Format("2006-01-02")
	rows, err := database.SqlDB.GetAll("SELECT u.nick_name, u.avatar_url, a.* FROM attendance AS a LEFT JOIN user AS u ON a.userId = u.id AND a.ruleId = ? WHERE a.create_time > ? group by a.userId having count(*)>1", id, toDay)
	if err != nil {
		fmt.Println(err)
		return nil, errors.New("查询失败")
	}
	return rows, nil
}

func Delete(id string) error {
	if _, err := database.SqlDB.Delete("rule", fmt.Sprintf("id=%s", id)); err != nil {
		return errors.New("删除失败")
	}
	return nil
}